<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>调度监控</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div>
      <div style="position: relative; background: white;">
        <!-- 地图 -->
        <div id="container" class="mapLoc"></div>
        <!-- 左边 -->
        <div class="dispath_shuax">
          <font>{{time}}</font>&nbsp;秒后刷新
        </div>
        <div class="dispatch_left">
          <div class="dispatch_lb" @scroll="scroll($event, 0)" v-show="expand1">
            <div style="width: 298px; margin: 0 14px; font-size:12px;">
              <a-input-group compact>
                <a-select v-model="leftSearchForm.orderType" style="width: 98px;">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="(v) in OrderOptions" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
                <a-input-search
                  v-model="leftSearchForm.word"
                  placeholder="公司编号/运单号/箱号/封号"
                  style="width: 200px"
                  @search="() => {handleLeftSubmit(); queryDispatchTruckOrderCount()}"
                />
              </a-input-group>
              <a-tabs
                :default-active-key="2"
                size="small"
                :tabBarStyle="{'width': '298px', 'marginTop': '10px'}"
                :tabBarGutter="5"
                @change="leftTabChange"
              >
                <a-tab-pane :key="2" :tab="`待派单(${orderListNum.waitDistributeCount||0})`"></a-tab-pane>
                <a-tab-pane :key="3" :tab="`司机待接单(${orderListNum.driverWaitGetCount||0})`"></a-tab-pane>
                <a-tab-pane :key="4" :tab="`司机待出发(${orderListNum.driverWaitGoCount||0})`"></a-tab-pane>
              </a-tabs>
            </div>
            <!-- 订单数据显示 -->
            <div class="order_leftover">
              <left-order-items
                v-show="orderList.length>0"
                :source="orderList"
                :selectId="currentSelelcted.order.orderTruckId"
                @click="chooseOrder"
              />
              <a-empty v-show="orderList.length===0" />
              <p style="text-align: center; height: 30px; margin-bottom:0;">
                <a-spin :spinning="orderSpinning" />
              </p>
            </div>
          </div>
          <div class="dispatch_ann">
            <div>
              <a-icon type="sync" @click="refreshIt" />
            </div>
            <div @click="() => expand1=!expand1">
              <a-icon :type="expand1?'double-left':'double-right'" />
            </div>
          </div>
        </div>

        <!-- 右边 -->
        <div class="dispatch_right">
          <div class="dispatch_carb" v-show="expand2">
            <div style="width: 220px; margin: 0 14px; font-size:12px;">
              <a-input-group compact>
                <a-select v-model="rightSearchForm.isSelfOperation" style="width: 70px;">
                  <a-select-option key>全部</a-select-option>
                  <a-select-option v-for="(v) in SelfOperationOptions" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
                <a-input-search
                  v-model="rightSearchForm.word"
                  placeholder="姓名/手机号码/车牌号"
                  style="width: 150px"
                  @search="() => refreshIt()"
                />
              </a-input-group>
              <a-tabs
                default-active-key
                size="small"
                :tabBarStyle="{'width': '220px', 'marginTop': '10px'}"
                :tabBarGutter="5"
                @change="rightTabChange"
              >
                <a-tab-pane key :tab="`全部(${driverListNum.totalNum||0})`"></a-tab-pane>
                <a-tab-pane :key="1" :tab="`在线(${driverListNum.onlineNum||0})`"></a-tab-pane>
                <a-tab-pane :key="2" :tab="`离线(${driverListNum.offlineNum||0})`"></a-tab-pane>
              </a-tabs>
            </div>
            <!-- 司机列表 -->
            <div class="order_leftover">
              <right-driver-items
                v-show="driverList.length>0"
                :source="driverList"
                :selectId="currentSelelcted.driver.tractorId"
                @click="chooseDriver"
                @operateCar="operateCar"
              />
              <a-empty v-show="driverList.length===0" />
              <p style="text-align: center; height: 30px; margin-bottom:0">
                <a-spin :spinning="driverSpinning" />
              </p>
            </div>
          </div>
          <div class="dispatch_cann">
            <div @click="() => expand2=!expand2">
              <a-icon :type="!expand2?'double-left':'double-right'" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 地图信息框 -->
    <mapCarinfo v-if="driverList.length>0" ref="carinfo" :car="carInfo" @operateCar="operateCar" />

    <!-- 派单 -->
    <a-modal
      :visible="dispatchVisible"
      title="确定派单"
      centered
      destroyOnClose
      :maskClosable="false"
      @ok="dispatchItem"
      @cancel="cancelDispatch"
    >
      <div>
        <a-card :bordered="false" :bodyStyle="{background: '#ececec'}">
          <p>
            车辆：{{currentSelelcted.driver.tractorNumber}}
            {{currentSelelcted.driver.trailerNumber && currentSelelcted.driver.isSelfOperation===0 ? `·${currentSelelcted.driver.trailerNumber}` : ''}}
            <span
              v-if="currentSelelcted.driver.isSelfOperation===1"
              class="selfFlag"
            >自营</span>
          </p>
          <p>
            司机：{{currentSelelcted.driver.name}}
            {{currentSelelcted.driver.phone ? `·${currentSelelcted.driver.phone}` : ''}}
            <span
              v-if="currentSelelcted.driver.isSelfOperation===1"
              class="selfFlag"
            >自营</span>
          </p>
        </a-card>
        <a-form :labelCol="{span: 4}" :wrapperCol="{span: 16}" style="margin-top: 21px">
          <a-form-item label="选择类型">
            <a-radio-group :options="options" v-model="dispatchForm.dispatchType" />
          </a-form-item>
          <a-form-item label="提箱类型">
            <a-radio-group
              :options="optionsNew"
              v-model="dispatchForm.dispatchEmptyOrHeavy"
              @change="onChangeEoh"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 跟踪 -->
    <a-modal
      width="900px"
      :visible="trackVisible"
      title="跟踪"
      :footer="null"
      centered
      destroyOnClose
      :maskClosable="false"
      @cancel="cancelTrack"
    >
      <trackInfo v-if="trackVisible" :id="trackId" />
    </a-modal>

    <!-- 回放 -->
    <!-- <a-modal width="1100px"
      :visible="visible" title="回放" :footer="null" centered destroyOnClose :maskClosable="false"
      @cancel="cancelBack">
      <div v-if="visible">
        <iframe :src="`http://pageapi.gpsoo.net/third?method=jump&page=playback&locale=zh-cn&account=%E4%BD%B3%E7%89%B9%E7%89%A9%E6%B5%81&target=${carInfo.imei}&appkey=ad043648af6f54dcac8f8f6caa5b4649`" width="100%" height="600"></iframe>
      </div>
    </a-modal>-->
  </div>
</template>

<script>
import mapCarinfo from './mapCarinfo'
import trackInfo from './track'
import {queryDispatchTruckOrderList, queryDispatchtTruckList, orderTruckDispatchSingle, queryDispatchTruckOrderCount, queryTruckOrderDispatchInfo} from '@/api/landCenter'
import {GD_KEY} from '@/common/config'
import {OrderOptions, SelfOperationOptions} from '../options'
import '@@/css/dispatch.css'
import car0 from '@@/images/car_green.png'
import car1 from '@@/images/car_red.png'
import car3 from '@@/images/car_off.png'
import car4 from '@@/images/car_yellow.png'
import AMapLoader from '@amap/amap-jsapi-loader'
import leftOrderItems from './leftOrderItems'
import rightDriverItems from './rightDriverItems'

const carIcons = [car0, car1, null, car3, car4] // 0:正常数据 green 3:设备离线 off 4:设备静止 yellow
const options = [
  { label: '提箱离港', value: 1 },
  { label: '空车离港', value: 2 },
  { label: '套箱接单', value: 3 }
]
const optionsNew = [
  { label: '空箱', value: 1 },
  { label: '重箱', value: 2 }
]

export default {
  data () {
    return {
      time: 10,
      GD_KEY,
      OrderOptions,
      options,
      optionsNew,
      SelfOperationOptions,
      map: null,
      AMap: null,
      infoWindow: null,
      expand1: true,
      expand2: true,
      orderSpinning: false,
      driverSpinning: false,
      orderList: [],
      driverList: [],
      driverListNum: {},
      orderListNum: {},
      currentSelelcted: {
        order: {},
        driver: {}
      },
      markerArr: [],
      mapMarkers: {},
      leftSearchForm: {
        status: 2, // 状态：2待派单、3司机待接单、4司机待出发
        orderType: '',
        word: ''
      },
      leftPageNum: 1,
      rightSearchForm: {
        gpsooStatus: '', // 1在线、2离线
        isSelfOperation: '',
        word: ''
      },
      rightPageNum: 1,
      // 信息框数据源
      carInfo: {},
      dispatchVisible: false,
      dispatchForm: {
        type: 2,
        orderTruckId: '',
        dispatchType: 1,
        dispatchEmptyOrHeavy: 1,
        dispatchList: [{
          driverId: '',
          tractorId: '',
          trailerId: ''
        }]
      },
      visible: false,
      timeout: null,
      trackVisible: false,
      trackId: null
    }
  },
  components: {
    [leftOrderItems.name]: leftOrderItems,
    [rightDriverItems.name]: rightDriverItems,
    mapCarinfo,
    trackInfo
  },
  methods: {
    // 定位车辆，并展示信息框
    setCarInfo (info) {
      this.infoWindow.close()

      const targetMarker = this.mapMarkers[`tractorId${info.tractorId}`]
      if (targetMarker) targetMarker.setTop(true) // 当前查看点置顶

      // 刷新选中
      this.driverList.forEach(v => {
        v.selected = false
        if (v.tractorId === info.tractorId) v.selected = true
      })
      this.driverList = [...this.driverList]

      this.carInfo = {...info} // 刷新信息框
      if (info.gpsooInfo) {
        this.infoWindow.setContent(this.$refs.carinfo.$el)
        this.infoWindow.open(this.map, new this.AMap.LngLat(info.gpsooInfo.lng, info.gpsooInfo.lat))
      }
    },
    // 点标记
    initPositionOfCars (cars) {
      this.map.remove(this.markerArr)
      const markers = []
      const mapMarkers = {}
      cars.forEach(item => {
        if (item.gpsooInfo) {
          const marker = new this.AMap.Marker({
            position: new this.AMap.LngLat(item.gpsooInfo.lng, item.gpsooInfo.lat),
            icon: carIcons[item.gpsooInfo.device_info_new], // 0:正常数据 3:设备离线 4:设备静止
            offset: new this.AMap.Pixel(-33, -64),
            title: `${item.tractorNumber} ▪ ${item.trailerNumber ? item.trailerNumber : ''}`
          })
          marker.on('click', e => {
            this.currentSelelcted.driver = item
          })
          markers.push(marker)
          mapMarkers[`tractorId${item.tractorId}`] = marker
        }
      })
      this.markerArr = markers
      this.mapMarkers = mapMarkers // 设置选中车辆层级
      this.map.add(markers)

      // 选中上次点击的车，没有或者第一次，就选中第一辆
      if (this.currentSelelcted.driver.tractorId) {
        this.currentSelelcted.driver = cars.filter(v => v.tractorId === this.currentSelelcted.driver.tractorId)[0] || cars[0]
      } else {
        this.currentSelelcted.driver = cars[0]
      }
    },
    // 循环刷新数据
    initTimeout () {
      if (this.time === 0) {
        this.handleRightSubmit()
        this.time = 10
      } else {
        this.time--
      }
      this.timeout = setTimeout(this.initTimeout, 1000)
    },
    refreshIt () {
      clearTimeout(this.timeout)
      this.time = 10

      this.handleLeftSubmit()
      this.handleRightSubmit()
      this.initTimeout()
    },

    // 滚动加载数据
    scroll (e, type) {
      let leftOrderListNode = e.target
      if (leftOrderListNode.offsetHeight + leftOrderListNode.scrollTop === leftOrderListNode.scrollHeight) {
        const a = this.scroll
        this.scroll = () => {}

        if (type === 0) {
          this.orderSpinning = true
          this.handleLeftSubmit(this.leftPageNum + 1).then(list => {
            this.orderList.push(list)
            this.orderSpinning = false
            this.scroll = a
          })
        }
      }
    },
    chooseOrder (order) {
      this.currentSelelcted.order = order
    },
    chooseDriver (car) {
      this.currentSelelcted.driver = car
    },

    // 车辆操作 派单，跟踪，回放
    operateCar (type) {
      if (type === 'dispatch') {
        this.dispatchIt()
      } else if (type === 'track') {
        this.trackIt()
      } else if (type === 'playback') {
        this.playback()
      }
    },
    dispatchIt () {
      if (!this.$root._bc.dispatch) {
        this.$message.error('您无此权限！')
        return
      }
      if (!this.currentSelelcted.order.orderTruckId) {
        this.$message.error('请先选择订单')
      } else if (!this.currentSelelcted.driver.tractorId) {
        this.$message.error('请先选择车辆')
      } else {
        this.options = [...options]
        this.optionsNew = [...optionsNew]

        // status 2待派单、3司机待接单、4司机待出发
        this.dispatchForm.type = this.currentSelelcted.order.status - 1 // type 1待派单 2司机待接单 3司机待出发
        this.dispatchForm.orderTruckId = this.currentSelelcted.order.orderTruckId
        this.dispatchForm.dispatchList = [{
          driverId: this.currentSelelcted.driver.driverId,
          tractorId: this.currentSelelcted.driver.tractorId,
          trailerId: this.currentSelelcted.driver.trailerId
        }]

        const isMultiAssign = this.currentSelelcted.order.dispatchList && this.currentSelelcted.order.dispatchList.length > 1 // 多人指派
        if (isMultiAssign && this.dispatchForm.type === 2) {
          this.options = options.filter(v => v.value === this.dispatchForm.dispatchType)
          this.optionsNew = optionsNew.filter(v => v.value === (this.dispatchForm.dispatchEmptyOrHeavy || 1))
        }

        if (this.dispatchForm.type !== 1) {
          queryTruckOrderDispatchInfo({orderTruckId: this.dispatchForm.orderTruckId}).then(rsp => {
            this.dispatchForm.dispatchType = rsp.data.dispatchType || 1
            this.dispatchForm.dispatchEmptyOrHeavy = rsp.data.dispatchEmptyOrHeavy || 1

            if (isMultiAssign && this.dispatchForm.type === 2) {
              this.options = options.filter(v => v.value === this.dispatchForm.dispatchType)
              this.optionsNew = optionsNew.filter(v => v.value === (this.dispatchForm.dispatchEmptyOrHeavy))
            }
          })
        }
        this.dispatchVisible = true
      }
    },
    dispatchItem () {
      orderTruckDispatchSingle(this.dispatchForm).then(rsp => {
        this.$message.success('派单成功')
        this.dispatchVisible = false
        this.refreshIt()
      })
    },
    cancelDispatch () {
      this.dispatchVisible = false
    },
    trackIt () {
      this.trackId = this.currentSelelcted.driver.tractorId
      this.trackVisible = true
    },
    cancelTrack () {
      this.trackId = null
      this.trackVisible = false
    },
    playback () {
      this.openCallback()
      // this.visible = true
    },
    cancelBack () {
      this.visible = false
    },

    // 回放
    openCallback () {
      window.open(`http://pageapi.gpsoo.net/third?method=jump&page=playback&locale=zh-cn&account=%E4%BD%B3%E7%89%B9%E7%89%A9%E6%B5%81&target=${this.carInfo.imei}&appkey=ad043648af6f54dcac8f8f6caa5b4649`, 'newwindow', 'height=700,width=1100,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no, left=200, top=200')
    },

    // 搜索
    queryDispatchTruckOrderCount () {
      queryDispatchTruckOrderCount({}).then(rsp => {
        this.orderListNum = rsp.data
      })
    },
    handleLeftSubmit (pageNum = 1) {
      return queryDispatchTruckOrderList({
        ...this.leftSearchForm,
        pageNum,
        pageSize: 10
      }).then(rsp => {
        this.leftPageNum = pageNum
        this.currentSelelcted.order = {}
        if (pageNum === 1) this.orderList = rsp.data.list
        else return rsp.data.list
      })
    },
    leftTabChange (key) {
      this.leftSearchForm.status = key
      this.queryDispatchTruckOrderCount()
      this.handleLeftSubmit()
    },
    handleRightSubmit (pageNum = 1) {
      return queryDispatchtTruckList({
        ...this.rightSearchForm,
        pageNum,
        pageSize: 999 // 查所有
      }).then(rsp => {
        this.driverListNum = rsp.data.info
        this.driverList = [...rsp.data.list]

        if (rsp.data.list.length > 0) {
          if (this.AMap) {
            this.initPositionOfCars(this.driverList) // 初始化地图车辆位置
          } else {
            AMapLoader.load({
              'key': this.GD_KEY,
              'version': '2.0',
              'plugins': ['AMap.Geocoder']
            }).then((AMap) => {
              // 地图缓存
              this.map = new AMap.Map('container')
              this.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -60), isCustom: true})
              this.AMap = AMap

              this.initPositionOfCars(this.driverList)
            }).catch(e => {
              // console.log(e)
            })
          }
        } else {
          this.map.remove(this.markerArr)
          this.currentSelelcted.driver = {}
        }
      })
    },
    rightTabChange (key) {
      this.rightSearchForm.gpsooStatus = key
      this.refreshIt()
    },
    onChangeEoh (e) {
      const _this = this
      if (e.target.value === 2) {
        this.$confirm({
          title: '切换至重箱，APP端无法输入箱号封号，确定切换吗？',
          onCancel () {
            _this.dispatchForm.dispatchEmptyOrHeavy = 1
          }
        })
      } else if (e.target.value === 1) {
        this.$confirm({
          title: '切换至空箱，APP端可变更箱号封号，确定切换吗？',
          onCancel () {
            _this.dispatchForm.dispatchEmptyOrHeavy = 2
          }
        })
      }
    }
  },
  mounted () {
    this.queryDispatchTruckOrderCount()
    this.handleLeftSubmit()
    this.handleRightSubmit()
    this.initTimeout()
  },
  watch: {
    'currentSelelcted.driver' (newDriver) {
      if (newDriver && newDriver.gpsooInfo) {
        this.map.setCenter(new this.AMap.LngLat(newDriver.gpsooInfo.lng, newDriver.gpsooInfo.lat))
        this.setCarInfo(newDriver)
      } else {
        this.infoWindow.close()
      }
    }
  },
  beforeDestroy () {
    if (this.timeout) {
      clearTimeout(this.timeout)
    }
  }
}
</script>

<style lang="less" scoped>
.mapLoc {
  width: 100%;
  height: 800px;
}
.ant-layout.ant-layout-has-sider > .ant-layout {
  overflow: auto;
}
.selfFlag {
  display: inline-block;
  border: 1px solid #1890ff;
  color: #1890ff;
  line-height: 12px;
  font-size: 12px;
  padding: 0 3px;
  margin-left: 8px;
  border-radius: 4px;
}
</style>
